package org.changchen.fgt.service.impl;

import org.changchen.fgt.config.SourceApiConfig;
import org.changchen.fgt.service.SourceRequestService;
import org.changchen.fgt.utils.Xml2JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpUtil;


/**   
* @ClassName:  SourceRequestServiceImpl   
* @Description:TODO   
* @author:     ChangChen 
* @date:       2024-01-08 15:07
* @Copyright:  2024 ChangChen. All rights reserved. 
*/
@Service
public class SourceRequestServiceImpl implements SourceRequestService{
	
	
	@Autowired
	@Qualifier(value = "customRestTemplate")
	private RestTemplate httpsRestTemplate;
	
	

	/**  
	 * <p>Title: getList</p>  
	 * <p>Description: </p>  
	 * @param page
	 * @param typeId
	 * @param word
	 * @param hour
	 * @return  
	 */
	@Override
	public JSONObject getList(String url, String dataType, Integer page, Integer typeId, String word, Integer hour) {
		
		url = url + "?ac=list";
		url = page != null ? url + "&pg=" + page : url;
		url = typeId != null ? url + "&t=" + typeId : url;
		url = word != null ? url + "&wd=" + word : url;
		url = hour != null ? url + "&h=" + hour : url;
	
		return get(url, dataType);
		
	}
	
	
	/**  
	 * <p>Title: getDetail</p>  
	 * <p>Description: </p>  
	 * @param page
	 * @param typeId
	 * @param ids
	 * @param hour
	 * @return  
	 */
	@Override
	public JSONObject getDetail(String url, String dataType, Integer page, Integer typeId, String ids, Integer hour) {
		
		url = url + "?ac=detail";
		url = page != null ? url + "&pg=" + page : url;
		url = typeId != null ? url + "&t=" + typeId : url;
		url = ids != null ? url + "&ids=" + ids : url;
		url = hour != null ? url + "&h=" + hour : url;
	
		return get(url, dataType);
	}
	
	
	/**   
	 * @Title:      get   
	 * @Description:请求资源   
	 * @param:      @param url
	 * @param:      @return      
	 * @return:     JSONObject      
	 * @throws   
	 */
	private JSONObject get(String url, String dataType) {
		
		// String result = httpsRestTemplate.getForObject(url, String.class);

		// 使用 hutool 请求工具类请求
		String result = HttpUtil.get(url);
		
		if(StringUtils.hasLength(result)) {
			if(SourceApiConfig.DATA_TYPE_JSON.equals(dataType)) {
				return JSON.parseObject(result);
			}
			return Xml2JsonUtil.xml2JSON(result);
		}
		
		return null;
	}
	
	
}
